package com.zzuli.yxy.filter;

import com.alibaba.fastjson.JSONObject;
import com.zzuli.yxy.entity.LoginUser;
import com.zzuli.yxy.enumeration.AppHttpCodeEnum;
import com.zzuli.yxy.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Objects;

/**
 * JWT过滤器，用户信息，SecurityContextHolder，后面的过滤器都会从这里获取认证的用户信息
 * @auther pony
 * @create 2023-03-07 21:06
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //1、获取token
        String token = httpServletRequest.getHeader("token");
        //2、解析token
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        String id = String.valueOf(JwtUtils.getUserIdByJwtToken(httpServletRequest));
        //3、从redis获取用户信息
        /*redis 取出来的是一个 object，即LoginUser，直接强转会报错，应该是序列化导致的，
        所以这里先转为map，再转为对象*/
        String redisKey = "login:"+id;
        LinkedHashMap<String, String> hashMap = new LinkedHashMap<>();
        hashMap = (LinkedHashMap<String, String>) redisTemplate.opsForValue().get(redisKey);
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(hashMap);
        LoginUser loginUser = jsonObject.toJavaObject(LoginUser.class);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException(AppHttpCodeEnum.NEED_LOGIN.getMessage());
        }
        //4、存入SecurityContextHolder
        //获取权限信息封装到Authentication
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
